package com.dapeis.service;

import java.util.Date;

import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import com.ag.core.exception.SysTipsException;
import com.ag.core.utils.AgAssert;
import com.ag.dao.DBService;
import com.ag.dao.IDao;
import com.dapeis.core.utils.StylistConstants;
import com.dapeis.dao.IMoneyLogExtMapper;
import com.dapeis.dao.IMoneyLogMapper;
import com.dapeis.domain.Collocation;
import com.dapeis.domain.MoneyLog;
import com.dapeis.domain.MoneyStatistics;
import com.dapeis.domain.Order;
import com.dapeis.domain.Plan;
import com.dapeis.domain.Requirement;
import com.dapeis.exception.moneyLog.SysMoneyLogException;

/**
 * @author 作者 E-mail: hzyuanyong@126.com
 * @version 创建时间：2017年5月23日 下午9:09:05 类说明
 */
@Service
public class MoneyLogService extends DBService<MoneyLog> {

    @Resource
    IMoneyLogMapper mapper;
    @Resource
    IMoneyLogExtMapper moneyLogExtMapper;
    @Resource
    RequirementService requirementService;
    @Resource
    CollocationService collocationService;

    @Override
    protected IDao<MoneyLog> getIDao() {
	return mapper;
    }

    /**
     * 抢单产生的记录
     * 
     * @param order
     * @return
     */
    public boolean task(Order order) {
	MoneyLog moneyLog = new MoneyLog();
	moneyLog.initMoneyLogTaskAndAward(order, getSourceType(order),
		StylistConstants.MoneyLog.Status.FREEZE, null);
	boolean result = insertSelective(moneyLog) > 0;
	if (result) {
	    return doAccountMoney(order, moneyLog);
	}
	throw new SysMoneyLogException();
    }

    /**
     * 服务完成
     * 
     * @return
     */
    public boolean finshService(Order order) {
	Example example = new Example(MoneyLog.class);
	Criteria criteria = example.createCriteria();
	criteria.andEqualTo(MoneyLog.PROPERTY_ORDERID, order.getId());
	criteria.andEqualTo(MoneyLog.PRORPTY_STATUS,
		StylistConstants.MoneyLog.Status.FREEZE);
	MoneyLog moneyLog = selectOneByExample(example);
	moneyLog.setStatus(StylistConstants.MoneyLog.Status.RECORDED);
	moneyLog.setModifyTime(new Date().getTime() / 1000);
	boolean result = updateByPrimaryKeySelective(moneyLog) > 0;
	if (result) {
	    return doAccountMoney(order, moneyLog);
	}
	throw new SysMoneyLogException();
    }

    /**
     * 打赏记录
     * 
     * @return
     */
    public boolean award(Order order, Plan plan) {
	MoneyLog moneyLog = new MoneyLog();
	moneyLog.initMoneyLogTaskAndAward(order, getSourceType(order),
		StylistConstants.MoneyLog.Status.RECORDED, plan);
	boolean result = insertSelective(moneyLog) > 0;
	if (result) {
	    return doAccountMoney(order, moneyLog);
	}
	throw new SysMoneyLogException();
    }

    /**
     * 审核操作
     * 
     * @param moneyLog
     * @return
     */
    public boolean doAudit() {
	//Boss模块实现
	return false;
    }

    /**
     * 提交取现
     * 
     * @return
     */
    public boolean enchashment(Integer collocationId, Integer money) {
	Collocation collocation = collocationService
		.selectByPrimaryKey(collocationId);
	AgAssert.isTrue(!(collocation.getTotalMoney() < money),
		SysTipsException.class, "可用余额不足!");
	// 测试时关闭
	// AgAssert.isTrue(withdrawalMoney < 200*100,
	// SysTipsException.class,"每次提现金额必须大于200");
	MoneyLog moneyLog = new MoneyLog();
	moneyLog.initOutlayMoneyLog(collocationId, money);
	boolean result = insertSelective(moneyLog) > 0;
	if (result) {
	    return doAccountMoney(null, moneyLog);
	}
	throw new SysMoneyLogException("申请提现失败");
    }

    public MoneyStatistics getCollocationAllStatistics(Integer collocationId) {
	MoneyStatistics ms = new MoneyStatistics();
	Collocation collocation = collocationService
		.selectByPrimaryKey(collocationId);
	ms.setAllInComeMoney(collocation.getAllInComeMoney());
	ms.setTotalMoney(collocation.getTotalMoney());
	ms.setFreezeMoney(collocation.getFreezeMoney());
	ms.setOutlayMoney(collocation.getOutlayMoney());

	ms.setConsultingSum(mapper.getSourceTypeSUM(
		StylistConstants.MoneyLog.Source.CONSULTING, collocationId));
	ms.setBuySum(mapper.getSourceTypeSUM(
		StylistConstants.MoneyLog.Source.BUY, collocationId));// 购买
	ms.setShopSum(mapper.getSourceTypeSUM(
		StylistConstants.MoneyLog.Source.SHOPPING, collocationId));//
	ms.setFinishingSum(mapper.getSourceTypeSUM(
		StylistConstants.MoneyLog.Source.FINISHING, collocationId));
	ms.setAwardSum(mapper.getSourceTypeSUM(
		StylistConstants.MoneyLog.Source.AWARD, collocationId));
	// 统计
	return ms;
    }

    /**
     * 根据订单获取SourceType
     * 
     * @param order
     * @return
     */
    public Integer getSourceType(Order order) {
	if (order.getType().equals(StylistConstants.Order.Type.REQUIREMENT)) {
	    Requirement requirement = requirementService
		    .selectByPrimaryKey(order.getLinkId());
	    if (null != requirement) {
		return requirement.getType();
	    }
	}
	if (order.getType().equals(StylistConstants.Order.Type.AWARD_PROGRAM)) {
	    return StylistConstants.MoneyLog.Source.AWARD;
	}
	throw new SysTipsException("错误的收支明细sourcType!");
    }

    @Transactional
    public boolean doAccountMoney(Order order, MoneyLog moneyLog) {
	Collocation collocation = collocationService.selectForLock(moneyLog
		.getCollocationId());
	if (null != order) {// 打赏和抢单都有订单,提现没有订单
	    // 打赏直接入账
	    if (order.getType().equals(
		    StylistConstants.Order.Type.AWARD_PROGRAM)) {
		collocation.setAllInComeMoney(collocation.getAllInComeMoney()
			+ moneyLog.getMoney());
		collocation.setTotalMoney(collocation.getTotalMoney()
			+ moneyLog.getMoney());
	    }
	    // 抢单-->冻结--->服务完成(入账)
	    if (order.getType().equals(StylistConstants.Order.Type.REQUIREMENT)) {
		// 冻结[1 增加总金额--->2.增加冻结金额]
		if (moneyLog.getStatus() == StylistConstants.MoneyLog.Status.FREEZE) {
		    collocation.setAllInComeMoney(collocation
			    .getAllInComeMoney() + moneyLog.getMoney());
		    collocation.setFreezeMoney(collocation.getFreezeMoney()
			    + moneyLog.getMoney());
		}
		// 服务完成 //[1.增加可用月---2.减去冻结金额]
		if (moneyLog.getStatus() == StylistConstants.MoneyLog.Status.RECORDED) {
		    if (collocation.getFreezeMoney() < moneyLog.getMoney())
			throw new SysTipsException("该账户资金出现问题");
		    collocation.setTotalMoney(collocation.getTotalMoney()
			    + moneyLog.getMoney());
		    collocation.setFreezeMoney(collocation.getFreezeMoney()
			    - moneyLog.getMoney());
		}
	    }
	} else {
	    // 提现-->冻结--->已转账--->入账 待实现
	    if (moneyLog.getSourceType() == StylistConstants.MoneyLog.Source.OUTLAY) {
		// 申请成功 1.可用余额减少 2.增加冻结金额
		if (moneyLog.getStatus() == StylistConstants.MoneyLog.Status.OUTLAY_COMMIT) {
		    collocation.setTotalMoney(collocation.getTotalMoney()
			    - moneyLog.getMoney());
		    collocation.setFreezeMoney(collocation.getFreezeMoney()
			    + moneyLog.getMoney());
		}
		// 确认转账 1.减少冻结金额 2.增加提现记录
		if (moneyLog.getStatus() == StylistConstants.MoneyLog.Status.OUTLAY_AUDIT_SUCCESS) {
		    collocation.setFreezeMoney(collocation.getFreezeMoney()
			    - moneyLog.getMoney());
		    collocation.setOutlayMoney(collocation.getOutlayMoney()
			    + moneyLog.getMoney());
		}
		// 信息有误 1.增加可用金额 2.减少冻结金额
		if (moneyLog.getStatus() == StylistConstants.MoneyLog.Status.OUTLAY_AUDIT_FAIL) {
		    collocation.setTotalMoney(collocation.getTotalMoney()
			    + moneyLog.getMoney());
		    collocation.setFreezeMoney(collocation.getFreezeMoney()
			    - moneyLog.getMoney());
		}
	    }
	}
	return collocationService.updateByPrimaryKeySelective(collocation) > 0;
    }

    public IMoneyLogExtMapper getMoneyLogExtMapper() {
	return moneyLogExtMapper;
    }

}
